import axios from 'axios';
import { Message } from 'element-ui';
import qs from 'qs';

axios.interceptors.request.use(
  (config) => {
    config.headers.token = sessionStorage.getItem('authorization');

    const method = config.method.toLowerCase();

    // 对于POST、PUT、PATCH等方法，默认使用x-www-form-urlencoded
    if (['post', 'put', 'patch'].includes(method)) {
      // 如果未手动设置Content-Type，则自动设置
      if (!config.headers['Content-Type']) {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        // 转换数据格式
        config.data = qs.stringify(config.data);
      }
    }
    // 对于GET、DELETE等方法，默认使用application/json
    else if (['get', 'delete', 'head', 'options'].includes(method)) {
      if (!config.headers['Content-Type']) {
        config.headers['Content-Type'] = 'application/json';
      }
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    // console.log('axios interceptors response => ', response)
    if (response.status === 200) {
      if (response.data.code === 200) {
        return response;
      } else if (response.data.code === 401) {
        Message.error('请重新登陆');
        location.href = '/#/login';
      } else {
        return Promise.reject(response.data);
      }
    } else {
      throw new Error('接口异常 Http Code: ' + response.status);
    }
  },
  (response) => {
    Message.error('接口异常:' + response.status);
    throw new Error('接口异常 Http Code: ' + response.status);
  }
);

// axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
// 允许携带cookie
// axios.defaults.withCredentials = true

export default axios;
